<?php
/**
 * @package  account
 */

class WithdrawalGridFieldDetailForm extends GridFieldDetailForm {
}

class WithdrawalGridFieldDetailForm_ItemRequest extends GridFieldDetailForm_ItemRequest {
    private static $allowed_actions = array(
        'edit',
        'view',
        'ItemEditForm',
        'doPrint'
    );
    
    public function updateCMSActions() {
        $actions = FieldList::create();
		
		if($this->record->canPrint()){
			$printButton = FormAction::create('doPrint', _t('WithdrawalGridFieldDetailForm.BUTTONPRINT', 'Print'))->setAttribute('data-icon', 'grid_print')->setAttribute('data-print-link', $this->Link('doPrint'))->setUseButtonTag(true);
			$actions->push($printButton);
		}
		
    	if($this->record->canReject()){
            $rejectButton = FormAction::create('doRejectWithdrawal', _t('WithdrawalGridFieldDetailForm.BUTTONREJECT', 'Reject'))->setAttribute('data-icon', 'decline')->setUseButtonTag(true);
            $actions->push($rejectButton);
		}
        
		if($this->record->canApprove()){
            $approveButton = FormAction::create('doApproveWithdrawal', _t('WithdrawalGridFieldDetailForm.BUTTONAPPROVE', 'Approve'))->setAttribute('data-icon', 'accept')->setUseButtonTag(true);
            $actions->push($approveButton);
		}
        return $actions;
    }

    public function ItemEditForm() {
    	Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
		Requirements::javascript(FRAMEWORK_DIR . '/javascript/i18n.js');
		Requirements::add_i18n_javascript('account/javascript/lang');
		Requirements::javascript('account/javascript/WithdrawalAction.js');
		
        $form = parent::ItemEditForm();
		$fields = FieldList::create(
             LiteralField::create('Statement', $this->record->ViewHTML())
        );
		if($this->record->Status == 'Pending'){
			$fields->push(TextField::create('Remark', $this->record->fieldLabel('Remark')));
		}
		$form->setFields($fields);
        $form->setActions($this->updateCMSActions());
        return $form;
    }

    public function doApproveWithdrawal($data, $form) {
        $controller = $this->getToplevelController();

        try {
            DB::getConn()->transactionStart();
            $form->saveInto($this->record);
            $id = $this->record->setField('Status', 'Approved')->write();
            DB::getConn()->transactionEnd();
            $this->record = DataObject::get_by_id($this->record->ClassName, $this->record->ID);
            $this->gridField->getList()->add($this->record);
        }
        catch(ValidationException $e) {
            DB::getConn()->transactionRollback();
            $form->sessionMessage($e->getResult()->message(), 'bad');
            $responseNegotiator = new PjaxResponseNegotiator( array(
                'CurrentForm' => function() use (&$form) {
                    return $form->forTemplate();
                },
                'default' => function() use (&$controller) {
                    return $controller->redirectBack();
                }

            ));
            if($controller->getRequest()->isAjax()) {
                $controller->getRequest()->addHeader('X-Pjax', 'CurrentForm');
            }
            return $responseNegotiator->respond($controller->getRequest());
        }

        $message = _t('WithdrawalGridFieldDetailForm.SUCCESS_APPROVED_WITHDRAWAL', 'Withdrawal has been successfully approved.');
        //end custom code

        $form->sessionMessage($message, 'good');

        if($this->gridField->getList()->byId($this->record->ID)) {
            // Return new view, as we can't do a "virtual redirect" via the CMS Ajax
            // to the same URL (it assumes that its content is already current, and doesn't reload)
            return $this->edit($controller->getRequest());
        } else {
            // Changes to the record properties might've excluded the record from
            // a filtered list, so return back to the main view if it can't be found
            $noActionURL = $controller->removeAction($data['url']);
            $controller->getRequest()->addHeader('X-Pjax', 'Content');
            return $controller->redirect($noActionURL, 302);
        }
    }

    public function doRejectWithdrawal($data, $form) {
        $controller = $this->getToplevelController();

        try {
            DB::getConn()->transactionStart();
            $form->saveInto($this->record);
            $id = $this->record->setField('Status', 'Rejected')->write();
            DB::getConn()->transactionEnd();
            $this->record = DataObject::get_by_id($this->record->ClassName, $this->record->ID);
            $this->gridField->getList()->add($this->record);
        }
        catch(ValidationException $e) {
            DB::getConn()->transactionRollback();
            SS_Log::log(new Exception(print_r($e->getMessage(), true)), SS_Log::NOTICE);
            $form->sessionMessage($e->getResult()->message(), 'bad');
            $responseNegotiator = new PjaxResponseNegotiator( array(
                'CurrentForm' => function() use (&$form) {
                    return $form->forTemplate();
                },
                'default' => function() use (&$controller) {
                    return $controller->redirectBack();
                }

            ));
            if($controller->getRequest()->isAjax()) {
                $controller->getRequest()->addHeader('X-Pjax', 'CurrentForm');
            }
            return $responseNegotiator->respond($controller->getRequest());
        }

        $message = _t('WithdrawalGridFieldDetailForm.SUCCESS_REJECTED_WITHDRAWAL', 'Withdrawal has been successfully rejected.');
        //end custom code

        $form->sessionMessage($message, 'good');

        if($this->gridField->getList()->byId($this->record->ID)) {
            // Return new view, as we can't do a "virtual redirect" via the CMS Ajax
            // to the same URL (it assumes that its content is already current, and doesn't reload)
            return $this->edit($controller->getRequest());
        } else {
            // Changes to the record properties might've excluded the record from
            // a filtered list, so return back to the main view if it can't be found
            $noActionURL = $controller->removeAction($data['url']);
            $controller->getRequest()->addHeader('X-Pjax', 'Content');
            return $controller->redirect($noActionURL, 302);
        }
    }
    
    public function doPrint(){
        return $this->record->ViewPrint();
    }
}
